<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 警告区域 -->
      <el-alert show-icon title="添加商品信息" type="info" center :closable="false"></el-alert>

      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 标签页 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0" :disabled="isOpen">
            <!-- 表单输入区域 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat" type="number">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="CatesListOption"
                :props="CatesList"
                @change="isSelectThreeLevel"
                style="width:350px"
                clearable
                filterable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1" :disabled="isOpen">
            <!-- 渲染表单的item项 -->
            <el-button class="addGoods" type="primary" @click="resetData" size="small">重新设置参数</el-button>
            <el-form-item
              :label="item.attr_name"
              prop="goods_name"
              v-for="item in manycheckBoxData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border v-for="(item2,i) in item.attr_vals" :key="i" :label="item2"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2" :disabled="isOpen">
            <el-form-item
              v-for="item in onlycheckBoxData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3" :disabled="isOpen">
            <!-- action:图片要上传到的后台Api接口
            on-preview:预览操作
            on-remove:删除操作
            -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4" :disabled="isOpen">
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor"></quill-editor>
            <el-button class="addGoods" type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
          <el-tab-pane class="okSubmit" label="完成填写" name="6" center disabled>
            <h3>提交完成</h3>
            <i class="el-icon-success" style="font-size: 128px;color:green"></i>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="查看图片" :visible.sync="previewVisible" @close="previewClose" width="60%" center>
      <img class="previewImg" center :src="previewPath" alt />
    </el-dialog>
  </div>
</template>

<script>
var _ = require("lodash");
export default {
  data: function() {
    return {
      isOpen: false,
      tabPosition: "left",
      activeIndex: "0",
      //   表单数据区
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_number: "",
        // 级联选择的值保存的地方
        goods_cat: [],
        pics: [],
        // 商品的详情描述
        goods_introduce: "",
        attrs: []
      },
      //   验证规则
      addFormRules: {
        goods_name: [
          {
            required: true,
            message: "商品名称不能为空",
            trigger: "blur"
          }
        ],
        goods_price: [
          {
            required: true,
            message: "商品价格不能为空",
            trigger: "blur"
          }
        ],
        goods_weight: [
          {
            required: true,
            message: "商品重量不能为空",
            trigger: "blur"
          }
        ],
        goods_number: [
          {
            required: true,
            message: "商品数量不能为空",
            trigger: "blur"
          }
        ],
        goods_cat: [
          {
            required: true,
            message: "商品分类不能为空(需要选择三级分类)",
            trigger: "change"
          }
        ]
      },
      //   级联的数据源
      CatesListOption: [],
      //   级联的配置项
      CatesList: {
        label: "cat_name",
        value: "cat_id",
        expandTrigger: "hover",
        children: "children"
      },
      manycheckBoxData: [],
      onlycheckBoxData: [],
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      headersObj: {
        Authorization: sessionStorage.getItem("token")
      },
      previewPath: "",
      previewVisible: false
    };
  },
  created: function() {
    this.getCateGories();
  },
  mounted: function() {},
  methods: {
    // 获取所有的三级分类做下拉数据
    getCateGories: async function() {
      const { data: res } = await this.$http.get("/categories");
      this.CatesListOption = res.data;
    },
    isSelectThreeLevel: function() {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.warning("需要选择三级分类哦");
        return (this.addForm.goods_cat = []);
      }
    },
    // 发起axios请求获取商品参数的复用函数
    getGoodsPrimary: async function() {
      const { data: res } = await this.$http.get(
        `categories/${this.addForm.goods_cat[2]}/attributes`,
        {
          params: {
            sel: "many"
          }
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("后台获取商品参数失败");
      }
      res.data.forEach(item => {
        item.attr_vals =
          item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
      });
      this.manycheckBoxData = res.data;
    },
    // 填写切换之前的钩子函数
    beforeTabLeave: async function(activeTagName, oldTagName) {
      //即将进入的页签activeTagName,现在在的页签oldTagName
      await this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          this.$message.warning("信息未填写完整,请您检查!");
          return Primise.reject("没填写完成");
        }
        this.activeIndex = activeTagName;
        return true;
      });
    },
    // 树形菜单被点击时候触发
    tabClick: async function(tab, event) {
      // 第二个判断条件是问了解决tabs点击到当前页面的时候才发起ajax请求,由于element的这个组件存在数据延迟,在上方:切换之前的钩子函数进行了赋值操作
      if (
        tab.index === "1" &&
        tab.index === this.activeIndex &&
        this.manycheckBoxData.length === 0
      ) {
        this.getGoodsPrimary(); //获取参数数据
      } else if (tab.index === "2" && tab.index === this.activeIndex) {
        const { data: res } = await this.$http.get(
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          {
            params: {
              sel: "only"
            }
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("后台获取商品属性失败");
        }
        this.onlycheckBoxData = res.data;
      }
    },
    // 重新设置参数按钮触发函数
    resetData: function() {
      this.getGoodsPrimary();
    },
    // 处理图片预览函数
    handlePreview: function(file) {
      this.previewPath = file.response.data.url;
      this.previewVisible = true;
    },
    // 处理图片删除操作
    handleRemove: function(file) {
      // 1 获取到图片的临时路径
      const filePath = file.response.data.tmp_path;
      // 2 从数组中找到这个图片对应的索引值
      const index = this.addForm.pics.findIndex(
        currentValue => currentValue.pic == filePath
      );
      // 删除数组的图片信息
      this.addForm.pics.splice(index, 1);
      console.log(this.addForm);
    },
    handleSuccess: function(res) {
      // 1,拼接得到一个图片信息对象
      const picInfo = { pic: res.data.tmp_path };
      this.addForm.pics.push(picInfo);
    },
    // 关闭查看图片对话框
    previewClose: function() {
      this.previewPath = "";
    },
    add: async function() {
      if (this.manycheckBoxData.length === 0) {
        return this.$message.warning("您还没有查看设置商品参数!");
      } else if (this.onlycheckBoxData.length === 0) {
        return this.$message.warning("您还没有查看设置商品属性!");
      }
      // 不能直接赋值改变数组为字符串,级联选择器冲突,方法:深拷贝 lodash  cloneDeep(Obj)

      var addFormDeep = _.cloneDeep(this.addForm);
      addFormDeep.goods_cat = addFormDeep.goods_cat.join(",");
      // 处理动态参数
      this.manycheckBoxData.forEach(item => {
        this.addForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        });
      });
      // 处理静态属性
      this.onlycheckBoxData.forEach(item => {
        this.addForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        });
      });
      addFormDeep.attrs = this.addForm.attrs;
      console.log(addFormDeep);

      const { data: res } = await this.$http.post("/goods", addFormDeep);
      if (res.meta.status !== 201) {
        return this.$message.error("提交商品失败了");
      }
      this.activeIndex = "6";
      this.isOpen = true;
      setTimeout(() => {
        this.$router.push("/goods");
      }, 2000);
      this.$message.success("提交商品成功了");
    }
  }
};
</script>
<style lang='less' scoped>
.el-steps {
  margin: 10px 0;
}
.box-card {
  height: calc(100vh - 150px);
  overflow-y: scroll;
}
.el-checkbox {
  margin: 0 !important;
  margin-left: 10px !important;
}
.previewImg {
  max-height: 95%;
  max-width: 100%;
  text-align: center !important;
  display: inline-block;
}
.addGoods {
  margin-top: 20px;
}
.okSubmit {
  text-align: center;
}
.el-tabs.el-tabs--left {
  height: calc(100vh - 394px) !important;
}
</style>